#pragma once
#include "ResourceManagers.h"
#include "Objects.h"

#include <Box2D/Box2D.h>


class Scene : public Entity
{
public:
	Scene(sf::RenderWindow* window,sf::Vector2f gravity = sf::Vector2f(0,20.0f))
	{
		rwWindow = window;
		vView = rwWindow->GetView();
		rwWindow->SetView(vView);
		


		mImageManager = new ImageManager();
		bRoot = true;

		bWorld = new b2World(b2Vec2(gravity.x,gravity.y),true);

	}
	~Scene()
	{
		for (unsigned int i = 0; i < vEntities.size(); i++)
		{
			delete vEntities[i];
		}
		if (mImageManager)
		{
			delete mImageManager;
		}

		delete bWorld;
	}

	//Add Entity to scene
	Entity * AddEntity(Entity * newEntity)
	{
		newEntity->Renderer = rwWindow;
		newEntity->nParent = this;
		newEntity->mImageManager = this->mImageManager;
		newEntity->bWorld = this->bWorld;


		//Init the scene entity.
		newEntity->Init();
		vEntities.push_back(newEntity);
		return newEntity;
	}

	//Remove Entity from scene
	Entity * RemoveEntity(Entity * delEntity)
	{
		for (unsigned int i = 0; i < vEntities.size(); i++)
		{
			if (vEntities[i] == delEntity)
			{
				vEntities.erase(vEntities.begin()+i);
			}
		}
		return delEntity;
	}

	//Update Scene
	void Update()
	{

		//Loc = curLoc + u(destLoc - curLoc) u = %[0,1] 
		if (eFollow != NULL)
		{
			vView.SetCenter(vView.GetCenter() + 0.1f*((eFollow->GetPosition()+eFollow->GetVelocity()) - vView.GetCenter()));
		}


		for (unsigned int i = 0; i < vEntities.size(); i++)
		{
			vEntities[i]->Update();
		}
		//bWorld->ClearForces();
		bWorld->Step(1.0f/60.0f,6,2);

		rwWindow->SetView(vView);
		//printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
	}

	//Render Scene
	void Render()
	{
		for (unsigned int i = 0; i < vEntities.size(); i++)
		{
			vEntities[i]->Draw();
		}
	}

	void SetFollow(Entity* eEntity)
	{
		eFollow = eEntity;
		vView.SetCenter(eFollow->GetPosition());
	}


private:
	//Scene Entities
	std::vector<Entity*> vEntities;

	//Entity for the camera to follow.
	Entity* eFollow;

	//Render window
	sf::RenderWindow* rwWindow;
	sf::View vView;


	//Box2D world
	b2World* bWorld;

	//Image Manager
	ImageManager* mImageManager;
};